///
/// ProjectName: ncmflutter
/// Author: yangjie
/// CreateDate: 2021/2/1 5:01 PM
/// Copyright: ©2021 NEW CORE Technology Co. Ltd. All rights reserved.
/// Description: 可拖动展开的控件
///
import 'dart:math' as math;

import 'package:flutter/material.dart';

const double kPanelTitleHeight = 32;

class DragDropPanel extends StatefulWidget {
  const DragDropPanel({
    Key? key,
    this.headWidget,
    this.title,
    this.child,
    this.expand = false,
    this.expandHeight,
    this.foldHeight,
    this.onExpand,
    this.titleHeight = kPanelTitleHeight,
    this.showBar = true,
    this.enableDrag = true,
  }) : super(key: key);

  final Widget? title;
  final double? titleHeight;

  /// 自定义headWidget 设置后 title、titleHeight则无效
  final Widget? headWidget;
  final Widget? child;
  final bool expand;
  final double? expandHeight;
  final double? foldHeight;
  final ValueChanged<bool>? onExpand;
  final bool showBar;
  final bool enableDrag;

  @override
  State<StatefulWidget> createState() {
    return _BackdropPanelState();
  }
}

///手势区域
class _BackdropPanelState extends State<DragDropPanel>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  double _kPanelTopPaddingHeight = 0;
  double _backdropHeight = 0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 300),
      value: widget.expand ? 1.0 : 0.0,
      vsync: this,
    )..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          widget.onExpand?.call(true);
        }
        if (status == AnimationStatus.dismissed) {
          widget.onExpand?.call(false);
        }
      });
  }

  @override
  void didUpdateWidget(DragDropPanel oldWidget) {
    if (widget.expand) {
      _controller.forward();
    } else {
      _controller.reverse();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  ///点击手势区域
  // void _toggleBackdropPanelVisibility() {
  //   if (_controller.isAnimating) {
  //     return;
  //   }
  //   if (_controller.isCompleted) {
  //     _controller.reverse();
  //   } else {
  //     _controller.forward();
  //   }
  // }

  void _handleDragUpdate(DragUpdateDetails details) {
    if (!widget.enableDrag) return;
    if (_controller.isAnimating) return;
    _controller.value -= details.primaryDelta! / (_backdropHeight);
  }

  void _handleDragEnd(DragEndDetails details) {
    if (!widget.enableDrag) return;
    if (_controller.isAnimating ||
        _controller.status == AnimationStatus.completed) return;

    final double flingVelocity =
        details.velocity.pixelsPerSecond.dy / _backdropHeight;

    if (flingVelocity < 0.0)
      _controller.fling(velocity: math.max(2.0, -flingVelocity));
    else if (flingVelocity > 0.0)
      _controller.fling(velocity: math.min(-2.0, -flingVelocity));
    else
      _controller.fling(velocity: _controller.value < 0.5 ? -2.0 : 2.0);
  }

  @override
  Widget build(BuildContext context) {
    var headWidget = widget.headWidget ??
        Container(
          height: widget.titleHeight ?? kPanelTitleHeight,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
            boxShadow: [
              BoxShadow(
                blurRadius: 6,
                offset: Offset(0, -2),
                color: Color.fromRGBO(0, 0, 0, 0.1),
              )
            ],
          ),
          // padding: const EdgeInsetsDirectional.only(start: 8.0),
          alignment: AlignmentDirectional.centerStart,
          child: Stack(
            children: <Widget>[
              Column(
                children: <Widget>[
                  Offstage(
                    offstage: !widget.showBar,
                    child: Padding(
                      padding: const EdgeInsets.only(top: 4),
                      child: Center(
                        child: Container(
                          width: 40,
                          height: 4,
                          decoration: BoxDecoration(
                              color: Colors.grey[400],
                              borderRadius: BorderRadius.circular(2)),
                        ),
                      ),
                    ),
                  ),
                  Expanded(child: Container())
                ],
              ),
              if (widget.title != null) widget.title!
            ],
          ),
        );
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
      //获取设备尺寸
      final panelSize = constraints.biggest;

      //折叠是距离顶部的高度
      _backdropHeight = panelSize.height;
      //自定义顶部导航栏高度，展开时距离顶部的区域
      _kPanelTopPaddingHeight = 0;
      _kPanelTopPaddingHeight += MediaQuery.of(context).padding.top;

      if (widget.foldHeight != null) {
        _backdropHeight = _backdropHeight - widget.foldHeight!;
        print("_backdropHeight = $_backdropHeight");
      }

      if (widget.expandHeight != null) {
        _kPanelTopPaddingHeight = _backdropHeight - widget.expandHeight!;
        if (_kPanelTopPaddingHeight < 0) {
          // 键盘弹出场景，修正顶部高度
          _kPanelTopPaddingHeight = 25;
        }
      }

      final Animation<RelativeRect> panelAnimation = _controller.drive(
        RelativeRectTween(
          //收起的时候的位置
          begin: RelativeRect.fromLTRB(
            0.0,
            _backdropHeight,
            0.0,
            0.0,
          ),
          //展开的时候的位置
          end: RelativeRect.fromLTRB(
            0.0,
            _kPanelTopPaddingHeight,
            0.0,
            0.0,
          ),
        ),
      );

      return Stack(
        children: [
          PositionedTransition(
            rect: panelAnimation,
            child: Material(
              elevation: 2.0,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(16.0),
                topRight: Radius.circular(16.0),
              ),
              // color: NCThemeDataC2.defaultTheme.background,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onVerticalDragUpdate: _handleDragUpdate,
                    onVerticalDragEnd: _handleDragEnd,
                    //onTap: _toggleBackdropPanelVisibility,
                    child: headWidget,
                  ),
                  Expanded(child: widget.child!),
                ],
              ),
            ),
          ),
        ],
      );
    });
  }
}
